package com.wwk.controller;

import com.wwk.constant.MessageConstant;
import com.wwk.entity.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Classname UserController
 * @Description TODO
 * @Date 2020/11/12 18:25
 * @Created by wwk
 * @Author wwk
 */
@RestController
@RequestMapping("/user")
public class UserController {
    //获取当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername()throws Exception{
    /**
     * Spring
     Security在认证成功后会将用户信息保存到框架提供的上下文对象中，所以此处我们就可以调用Spring
     Security框架提供的API获取当前用户的username并展示到页面上。
     */
    //此User 为org.springframework.security.core.userdetails.User
        final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(user);
        if(user!=null){
            String username=user.getUsername();
            return  new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }else{
            return new Result(false,MessageConstant.GET_USERNAME_FAIL);
        }
    }
}
